package com.paradogs.framework.core.netty;

import com.paradogs.framework.core.netty.server.PRConnection;
import com.paradogs.framework.core.netty.server.ServerProperties;
import io.netty.channel.Channel;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: yumi
 * @date: 2023/11/27  13:40
 * @Description: TODO
 */
public class PRConnHolder {

    private static Map<String, List<PRConnection>> typeConnMap = new ConcurrentHashMap<>();
    private static Map<Channel, PRConnection> channelConnMap = new ConcurrentHashMap<>();

    public static void addConn(String type, PRConnection conn) {
        if (!typeConnMap.containsKey(type)) {
            typeConnMap.put(type,  new ArrayList<>());
        }
        typeConnMap.get(type).add(conn);
        channelConnMap.put(conn.getChannel(), conn);
    }

    public static void initConn(Channel channel, ServerProperties properties) {
        addConn(properties.getType(), new PRConnection(channel, properties));
    }

    public static List<PRConnection> getConns(String type) {
        if (!typeConnMap.containsKey(type)) {
            return new ArrayList<>();
        }
        return typeConnMap.get(type);
    }

    public static PRConnection getConn(String type) {
        if (!typeConnMap.containsKey(type)) {
            return null;
        }
        return typeConnMap.get(type).get(0);
    }

    public static PRConnection getConn(Channel channel) {
        return channelConnMap.get(channel);
    }

    public static void removeConn(String type) {
        for (PRConnection conn : typeConnMap.remove(type)) {
            channelConnMap.remove(conn.getChannel());
        }
    }

    public static PRConnection removeConn(Channel channel) {
        PRConnection conn = channelConnMap.remove(channel);
        if (conn != null) {
            List<PRConnection> list = typeConnMap.get(conn.getType());
            if (list != null) {
                Iterator<PRConnection> iterator = list.iterator();
                while (iterator.hasNext()) {
                    PRConnection next = iterator.next();
                    if (next == conn) {iterator.remove();}
                }
            }
        }
        return conn;
    }
}
